import axios from 'axios'
//用axios 记得 npm 一下
import {ElMessage} from 'element-plus'
const http = axios.create({
    baseURL:'https://v3pz.itndedu.com/v3pz',
    timeout:10000,
})

//添加拦截器
http.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么.
   const token =  localStorage.getItem('pz-token')
   //不需要添加token的api
   const whiteUrl = ['/get/code','/user/authentication','/login']
   if(token && !whiteUrl.includes(config.url)){
    //如果不在白名单就加token 
    config.headers['x-token'] = token
   }
   return config;
})
//相应拦截器

http.interceptors.response.use(function (response){
    //对接口异常数据，给用户提示
    if(response.data.code === -1) {
        ElMessage.warning(response.data.message)
    }
    if(response.data.code === -2){
        localStorage.removeItem('pz-token')
        localStorage.removeItem('pz-userInfo')
        window.location.href = window.location.origin
    }
    return response;
}, function (error) {
    return Promise.reject(error);
}
)

export default http